
package net.swa.index.web.action;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Required;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.swa.dewei.beans.entity.Battery;
import net.swa.dewei.beans.entity.CheXing;
import net.swa.dewei.beans.entity.DingDan;
import net.swa.dewei.beans.entity.LxKehu;
import net.swa.dewei.beans.entity.MenDian;
import net.swa.dewei.beans.entity.WeixinInfo;
import net.swa.dewei.service.BatteryService;
import net.swa.dewei.service.CheXingCityService;
import net.swa.dewei.service.DingDanService;
import net.swa.dewei.service.MenDianService;
import net.swa.index.util.WxStringUtil;
import net.swa.system.beans.entity.Dict;
import net.swa.system.service.ICommonService;
import net.swa.util.BuzConst;
import net.swa.util.DateUtils;
import net.swa.util.EncryptTool;
import net.swa.util.JsonResult;
import net.swa.util.MySecureProtocolSocketFactory;

/**
 * 跳转供移动设备浏览action
 * 
 * @author Administrator
 * 
 */
public class IndexAction extends AbstractBaseIndexAction
{
    private static final long serialVersionUID = 7868090805552756795L;

    private final Logger log = Logger.getLogger(IndexAction.class);

    private ICommonService commonService;

    /** 电池操作接口 **/
    private BatteryService batteryService;

    /**车型城市关系操作维护类**/
    private CheXingCityService cheXingCityService;

    /** 门店查询接口 */
    private MenDianService menDianService;

    /** 订单查询接口 */
    private DingDanService dingDanService;

    private DingDan model;

    // 车型列表
    //    private List<CheXing> chexList;

    /** 订单列表 */
    private List<DingDan> dingdans;

    //电池信息列表
    private List<Battery> betteryList;

    //电池信息列表 json
    private String betteryListJson;

    /**
     * modify by yuan xiao
     * 订单json数据
     */
    private String dingdansJson;

    private String json;

    private Long id;

    private Double lat;

    private Double lng;

    /** 微信id */
    private String wxid;

    /** 公众号id **/
    private String gzhId;

    /** 安全令牌 */
    private String token;

    // 附近没有店面时候 用户留下姓名
    private String lianxiName;

    // 附近没有店面时候 用户留下电话
    private String lianxiKefuTel;

    // 附近没有店面时候 用户留下地址
    private String lianxiAddr;

    // 省
    private String province;

    // 市
    private String city;

    // 县
    private String town;

    // 订单状态
    private String state;

    //当前日期
    private String nowDate;

    //当前小时
    private String nowHour;

    //oauth2 校验参数
    private String appid;

    //oauth2 校验参数
    private String redirect_uri;

    //地图上缩放级别
    private int level = 15;

    /**
     * 跳转到移动设备浏览主页面
     * 
     * @return
     * @throws Exception
     */
    public String main() throws Exception
    {
        //        chexList = commonService.search(null, null, CheXing.class, 100, "sort", "asc");
        model = new DingDan();
        setNow();
        if (!StringUtils.isBlank(wxid))
        {
            // 将wxid 保存到session
            setSessionAttribute("wxid", wxid);
            addCookie("wxid", wxid);
            if (null != lat && null != lng)
            {
                model.setLat(lat);
                model.setLng(lng);
                //本身就是谷歌坐标系
                model.setBlat(lat);
                model.setBlng(lng);
                //谷歌坐标系转百度
                //                convertLatLng(Const.HTTP_BAIDU_CONVERT_URL2);
            }
            else
            {
                // 调微营销接口获取经纬度
                if (log.isDebugEnabled())
                {
                    log.debug("开始调微营销接口获取经纬度,gzhId:" + gzhId + " ,wxid=" + wxid);
                }
                if (!StringUtils.isBlank(gzhId))
                {
                    String http = BuzConst.HTTP_GETCLIENT_LOCATION + WxStringUtil.getSuffix(wxid, gzhId);
                    log.debug("开始调微营销接口获取经纬度路径：" + http);
                    String resp = MySecureProtocolSocketFactory.get(http);
                    JSONObject jsonObj = JSONObject.fromObject(resp.toString());

                    Object success = (Object) jsonObj.get("success");
                    if ((Boolean) success)
                    {
                        JSONObject gps = (JSONObject) jsonObj.get("gps");
                        if (log.isDebugEnabled())
                        {
                            log.debug("成功得到经纬度：" + gps);
                        }
                        if (null != gps)
                        {
                            Object t = gps.get("ts");
                            if (null != t)
                            {
                                try
                                {

                                    Long ts = Long.parseLong(t.toString().trim());
                                    if (log.isDebugEnabled())
                                    {
                                        log.debug("时间ts：" + ts);
                                    }
                                    if (DateUtils.checkTime(ts, BuzConst.MINUTE_FIVE))
                                    {
                                        lng = Double.parseDouble(gps.get("lng").toString().trim());
                                        lat = Double.parseDouble(gps.get("lat").toString().trim());
                                        if (log.isDebugEnabled())
                                        {
                                            log.debug("经纬度的信息 为lat:" + lat + ",lng:" + lng);
                                        }
                                    }
                                    else
                                    {
                                        if (log.isDebugEnabled())
                                        {
                                            log.debug("错误,经纬度的信息超时已经失效。。。。。。。。。。。");
                                        }
                                    }
                                }
                                catch (NumberFormatException e)
                                {
                                    e.printStackTrace();
                                    log.error("这个字符串不能转化成Long型的。");
                                }
                            }
                        }
                    }
                    else
                    {
                        if (log.isDebugEnabled())
                        {
                            log.debug("错误：" + jsonObj);
                        }
                    }
                }
            }
        }
        else
        {
            //setSessionAttribute("wxid", "admin");
            return "outTimeError";
        }
        // 获取车辆类型
        return "main";
    }

    private void setNow()
    {
        //        nowDate = DateFormat.getDateInstance().format((new Date()));
        //        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        nowDate = sdf.format((new Date()));
        Calendar c = new GregorianCalendar();
        nowHour = String.format("%02d", c.get(Calendar.HOUR_OF_DAY)) + ":" + String.format("%02d", c.get(Calendar.MINUTE));
    }

    /**
     * 根据车型，省市县，查询电池列表
     * 
     * @throws Exception
     **/
    public String ajaxQueryDianchi() throws Exception
    {
        JsonResult<Battery> json;
        if (log.isDebugEnabled())
        {
            log.debug("根据车型，省市县查询电池：id is" + id + ", province is " + province + ", city is " + city + ", town is " + town);
        }
        json = batteryService.queryDianchis(id, province, city, town);
        outJson(json);
        return null;
    }

    /**
     * 根据根据城市查询车型列表
     * 
     * @throws Exception
     **/
    public String ajaxQueryChexByCity() throws Exception
    {
        if (log.isDebugEnabled())
        {
            log.debug("根据城市查询车型：当前城市是：" + city + ",省：" + province + ",区县：" + town);
        }
        List<CheXing> list = cheXingCityService.queryChexByCity(province, city, town);
        outJson(list);
        return null;
    }

    /**
     * 根据经纬度获取位置文字
     * 
     * @return
     * @throws Exception
     */
    public String getLocation() throws Exception
    {
        if (null != lat && null != lng)
        {
            log.debug("获取位置信息----纠偏前为 x：" + lng + ",y:" + lat);
            //加纠偏后
            String http = BuzConst.HTTP_BAIDU_CONVERT_URL2 + "&y=" + lat + "&x=" + lng;
            String resp;
            String resp2 = null;
            try
            {
                resp = MySecureProtocolSocketFactory.get(http);
                JSONObject jsonObj = JSONObject.fromObject(resp.toString());
                if (null != jsonObj)
                {
                    if (jsonObj.get("error").toString().equals("0"))
                    {
                        String x = (String) jsonObj.get("x");
                        String y = (String) jsonObj.get("y");
                        log.debug("获取位置信息----纠偏数据结果解码前为 x：" + x + ",y:" + y);
                        lng = Double.parseDouble(EncryptTool.getFromBASE64(x));
                        lat = Double.parseDouble(EncryptTool.getFromBASE64(y));
                        log.debug("获取位置信息----纠偏后为 x：" + lng + ",y:" + lat);
                    }
                }
                String path = "http://api.map.baidu.com/geocoder/v2/?ak=790411bda172ff9496825d6ea740661d&location=" + lat + "," + lng + "&output=json&pois=0";
                log.debug("getLocationByGgLatlng  path is " + path);
                resp2 = MySecureProtocolSocketFactory.get(path);
                log.debug("getLocationByGgLatlng  is " + resp2);
            }
            catch (Exception e)
            {
                log.debug("调用百度纠偏接口失败！");
                e.printStackTrace();
            }
            finally
            {
                outString(resp2.toString());
            }
            //            URL url = new URL(path);
            //            InputStream in = url.openStream();
            //            StringBuilder json = new StringBuilder();
            //            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
            //            String line = null;
            //            while ((line = reader.readLine()) != null)
            //            {
            //                json.append(line);
            //            }
            //            log.debug("getLocation result is " + json.toString());
            //            outString(json.toString());
        }
        else
        {
            log.debug("传入经纬度出错");
            outError("经纬度获取失败");
        }
        return null;
    }

    /**
     * 根据经纬度获取位置文字
     * 此法主要避免js跨域访问，但是google接口限制查询次数，故不使用
     * @return
     * @throws Exception 
     * @throws Exception
     */
    public String getLocationByGgLatlng() throws Exception
    {
        if (null != lat && null != lng)
        {
            try
            {
                String path = BuzConst.HTTP_MAP_GEO_GOOGLE + "?latlng=" + lat + "," + lng + "&language=zh-CN&sensor=true";

                log.debug("getLocationByGgLatlng  path is " + path);
                String http = path;
                String resp;
                resp = MySecureProtocolSocketFactory.get(http);
                log.debug("getLocationByGgLatlng  is " + resp);
                outString(resp.toString());
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        else
        {
            log.debug("传入经纬度出错");
            outError("经纬度获取失败");
        }
        return null;
    }

    /**
     * 根据经纬度获取位置文字,高德地图
     * 此法主要避免js跨域访问，refer
     * @return
     * @throws Exception 
     * @throws Exception
     */
    public String getLocationByGaodeLatlng() throws Exception
    {
        if (null != lat && null != lng)
        {
            try
            {
                String path = BuzConst.HTTP_MAP_GEO_GAODE + "&location=" + lng + "," + lat;
                log.debug("getLocationByGaodeLatlng  path is " + path);
                String http = path;
                String resp;
                resp = MySecureProtocolSocketFactory.get(http);
                log.debug("getLocationByGaodeLatlng  is " + resp);
                outString(resp.toString());
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        else
        {
            log.debug("传入经纬度出错");
            outError("经纬度获取失败");
        }
        return null;
    }

    /**
     * 根据传入的经纬度，取方圆指定范围的店面
     * 
     * @throws Exception

    public String getMakers() throws Exception
    {
        if (null != lat && null != lng)
        {
            JsonResult<MenDian> json = menDianService.queryByLatLng(lat, lng);
            outJson(json);
        }
        else
        {
            outError("经纬度获取失败");
        }
        return null;
    }
     */
    /** 新增 **/
    public String saveDingDan() throws Exception
    {
        if (null != getSessionAttribute("wxid"))
        {
            wxid = getSessionAttribute("wxid").toString();
            model.setUserId(wxid);
        }
        else
        {
            wxid = getCookie("wxid").toString();
            model.setUserId(wxid);
        }
        model.setState("0");// 0初始状态
        model.setCrateDate(DateUtils.getCurrDate(null));
        model = doColumnFilter(model);//针对订单类型对一些字段做过滤
        String result = dingDanService.add(model);
        if (null != result)
        {
            outString(result);
        }
        else
        {
            outError("新增订单失败");
        }
        return null;
    }

    //针对订单类型对一些字段做过滤
    private DingDan doColumnFilter(DingDan model)
    {
        if (null != model)
        {
            if (!StringUtils.isBlank(model.getChangeType()))
            {
                //门店更换的，客户的信息不要
                if (BuzConst.DINGDAN_CHANGE_TYPE_MD.equals(model.getChangeType().trim()))
                {
                    model.setKehuName(null);
                    model.setLxTel(null);
                    //                    model.setAddress(null);
                    model.setTime(null);
                }
                else
                {//非门店更换的，将门店信息清空
                    model.setMendianId(null);
                    model.setMendianAddr(null);
                    model.setMendianLxr(null);
                    model.setMendianName(null);
                    model.setMenDianTel(null);
                }
                if (BuzConst.DINGDAN_CHANGE_TYPE_SM.equals(model.getChangeType().trim()))
                {
                    String[] keys = { "title", "key" };
                    Object[] values = new Object[] { BuzConst.CONFIG_INFO, BuzConst.CONFIG_SERVER_PRICE };
                    List<Dict> dl = commonService.search(Dict.class, keys, values);
                    if (null != dl && dl.size() > 0)
                    {
                        Dict d = dl.get(0);
                        model.setServerPrice(d.getValue());
                    }
                    else
                    {
                        model.setServerPrice("9.9");
                    }
                }
                else
                {
                    model.setServerPrice(null);
                }
                return model;
            }
        }
        return null;
    }

    /** 保存联系客服信息 */
    public String addLianxiKefu() throws Exception
    {
        LxKehu model = new LxKehu();
        model.setName(lianxiName);
        model.setAddr(lianxiAddr);
        model.setTel(lianxiKefuTel);
        model.setCrateDate(DateUtils.getCurrDate(null));
        commonService.commonAdd(model);
        outSuccess();
        return null;
    }

    /** 查询历史订单 
     * @throws UnsupportedEncodingException ***/
    public String queryHisDingdans() throws UnsupportedEncodingException
    {
        if (StringUtils.isBlank(wxid))
        {
            wxid = (String) getSessionAttribute("wxid");
            if (StringUtils.isBlank(wxid))
            {
                wxid = getCookie("wxid");
                if (StringUtils.isBlank(wxid))
                {
                    //如果这样还获取不到，就要使用高级接口了。
                    log.debug("I can not find wxid without u agree.");
                    appid = BuzConst.APPID;
                    String path = getRequest().getContextPath();
                    String basePath = getRequest().getScheme() + "://" + getRequest().getServerName() + path + "/index/proccessOauth.do";
                    redirect_uri = URLEncoder.encode(basePath, BuzConst.CODE_UTF8);
                    return "oauth2Check";
                }
            }
        }
        else
        {
            setSessionAttribute("wxid", wxid);
        }

        WeixinInfo info = commonService.findByAttribute(WeixinInfo.class, "openid", wxid);
        if (null == info)
        {
            dingdans = commonService.search("userId", wxid, DingDan.class, 10, "id", "desc");
            if (null != dingdans && dingdans.size() > 0)
            {
                for (DingDan o : dingdans)
                {
                    if (!StringUtils.isBlank(o.getCrateDate()))
                    {
                        o.setInvalidDate(DateUtils.getDatePlusHour(o.getCrateDate(), BuzConst.FORMAT_STRING1, BuzConst.FORMAT_STRING2, BuzConst.HOUR48));
                    }
                }
                /**
                 * 将list数据按json格式输出
                 */
                JSONArray ja = JSONArray.fromObject(dingdans);
                dingdansJson = ja.toString();
            }
            return "queryHisDingdans";
        }
        else if (info.isMendian())
        {
            String[] ss = { "wxid", "status" };
            Object[] vv = { wxid, 1 };
            List<MenDian> mlist = commonService.search(MenDian.class, ss, vv);
            if (null != mlist && mlist.size() > 0)
            {
                // 是门店用户
                MenDian m = commonService.search(MenDian.class, ss, vv).get(0);
                //                findByAttribute(MenDian.class, "wxid", wxid);
                if (null != m)
                {
                    dingdans = dingDanService.queryMyDingdans(m.getId());
                    if (null != dingdans && dingdans.size() > 0)
                    {
                        for (DingDan o : dingdans)
                        {
                            if (!StringUtils.isBlank(o.getCrateDate()))
                            {
                                o.setInvalidDate(DateUtils.getDatePlusHour(o.getCrateDate(), BuzConst.FORMAT_STRING1, BuzConst.FORMAT_STRING2, BuzConst.HOUR48));
                            }
                        }
                        JSONArray ja = JSONArray.fromObject(dingdans);
                        dingdansJson = ja.toString();
                    }
                }
                return "queryMyDingdans";
            }
            else
            {
                dingdans = commonService.search("userId", wxid, DingDan.class, 10, "id", "desc");
                return "queryHisDingdans";
            }
        }
        else
        {
            dingdans = commonService.search("userId", wxid, DingDan.class, 10, "id", "desc");
            if (null != dingdans && dingdans.size() > 0)
            {
                for (DingDan o : dingdans)
                {
                    if (!StringUtils.isBlank(o.getCrateDate()))
                    {
                        o.setInvalidDate(DateUtils.getDatePlusHour(o.getCrateDate(), BuzConst.FORMAT_STRING1, BuzConst.FORMAT_STRING2, BuzConst.HOUR48));
                    }
                }
                JSONArray ja = JSONArray.fromObject(dingdans);
                dingdansJson = ja.toString();
            }
            return "queryHisDingdans";
        }
    }

    /***
     * 处理获取code 根据其获取用户信息openId跳转
     * @return
     */
    public String proccessOauth()
    {
        String code = getRequestParameter("code");
        log.debug("调用oauth2.0 授权返回code is :" + code);
        if (!StringUtils.isBlank(code))
        {
            String http = BuzConst.HTTP_WX__WEB_OAUTH_CHECK + "?appid=" + BuzConst.APPID + "&secret=" + BuzConst.SECRET + "&code=" + code + "&grant_type=authorization_code";
            String resp = null;
            try
            {
                log.debug("调用oauth2.0 授权返回http is :" + http);
                resp = MySecureProtocolSocketFactory.get(http);
                JSONObject jsonObj = JSONObject.fromObject(resp.toString());
                log.debug("调用oauth2.0 授权返回jsonObj is :" + jsonObj);
                if (null != jsonObj)
                {
                    Object o = jsonObj.get("openid");
                    if (null != o)
                    {
                        log.debug("成功通过高级接口得到wxid:" + o);
                        wxid = o.toString();
                        return queryHisDingdans();
                    }
                }
            }
            catch (Exception e)
            {
                log.debug("调用oauth2.0授权后调用户信息出现异常:" + e);
                e.printStackTrace();
            }
        }
        //暂时返回超时
        return "outTimeError";
    }

    /**
     * 处理订单改变订单状态
     * 
     * @throws Exception
     **/
    public String processDingdan() throws Exception
    {
        if (null != id && !StringUtils.isBlank(state))
        {
            dingDanService.updateStatus(id, state);
            outSuccess();
        }
        else
        {
            outError("参数不合法");
        }
        return null;
    }

    /**
     * 根据车型，省市县，查询电池列表
     * 
     * @throws Exception
     **/
    public String queryBettery() throws Exception
    {
        if (null == model)
        {
            model = getModelSessionCookie();
        }
        if (null != model)
        {
            addModelSessionCookie(model);
            if (log.isDebugEnabled())
            {
                log.debug("查询订单：" + model);
            }
            if (null == model.getChexingId() || StringUtils.isBlank(model.getProvince()) || StringUtils.isBlank(model.getCity()) || StringUtils.isBlank(model.getTown()))
            {
                if (log.isDebugEnabled())
                {
                    log.error("订单数据缺失，根据车型，省市县查询电池：id is" + model.getChexingId() + ", province is " + model.getProvince() + ", city is " + model.getCity() + ", town is " + model.getCity());
                }
                model.setCity("未知城市");
                return "queryBettery";
            }
            betteryList = batteryService.queryBettys(model.getChexingId(), model.getProvince(), model.getCity(), model.getTown());
        }
        else
        {
            if (log.isDebugEnabled())
            {
                log.error("订单数据缺失，根据车型，省市县查询电池：");
            }
            return "outTimeError";
        }
        JSONArray ja = JSONArray.fromObject(betteryList);
        betteryListJson = ja.toString();
        return "queryBettery";
    }

    /***
     * 跳转到选择电池页面
     * @return
     */
    public String chooseService()
    {
        if (null == model)
        {
            model = getModelSessionCookie();
        }
        else
        {
            addModelSessionCookie(model);
        }
        if (null != model)
        {

            //convertLatLng(Const.HTTP_BAIDU_CONVERT_URL);
            addModelSessionCookie(model);
            if (log.isDebugEnabled())
            {
                log.debug("选择服务方式前，当前订单：" + model);
            }
            return "chooseService";
        }
        else
        {
            log.error("订单数据缺失ERROR");
            return "outTimeError";
        }
    }

    /***
     * 附近门店更换
     * 查询附近门店没有就到无网点
     * @return
     */
    public String changeTypeNear()
    {
        if (null != model)
        {
            addModelSessionCookie(model);
            if (log.isDebugEnabled())
            {
                log.debug("附近门店更换订单：" + model);
            }
        }
        else
        {
            model = getModelSessionCookie();
            if (null != model)
            {
                if (log.isDebugEnabled())
                {
                    log.debug("附近门店更换订单：" + model);
                }
            }
            log.error("订单数据缺失ERROR");
            return "outTimeError";
        }
        if ((null != model.getBlat()) && (null != model.getBlng()))
        {
            List<MenDian> list = menDianService.queryMendianByModelLatLng(model, 20);
            json = getJson(list);
            if (null != list && list.size() > 0)
            {
                getCenterFromList(list);
                return "changeTypeNear";
            }
            else
            {
                return "changeNoMendian";
            }
        }
        else
        {
            log.error("订单数据缺失ERROR:不应该到这儿经纬度丢失");
            return "outTimeError";
        }
    }

    //计算门店数据的中心点
    private void getCenterFromList(List<MenDian> list)
    {
        lat = lng = 0d;
        level = 16;
        int size = list.size();
        for (MenDian m : list)
        {
            if (null != m.getLatitude() && null != m.getLongitude())
            {
                lat = BuzConst.add(lat, m.getLatitude());
                lng = BuzConst.add(lng, m.getLongitude());
            }
            if (null != m.getDoubleDistance())
            {
                if (m.getDoubleDistance() > 500)
                {
                    level = 14;
                    if (m.getDoubleDistance() > 1000)
                    {
                        level = 13;
                        if (m.getDoubleDistance() > 4000)
                        {
                            level = 12;
                            if (m.getDoubleDistance() > 8000)
                            {
                                level = 11;
                                if (m.getDoubleDistance() > 9000)
                                {
                                    level = 10;
                                    if (m.getDoubleDistance() > 10000)
                                    {
                                        level = 9;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        lat = BuzConst.div(lat, size);
        lng = BuzConst.div(lng, size);
        log.debug("计算得到其中心坐标lat is " + lat + ",lng is " + lng);
    }

    /**上门方式加服务费***/
    private void setServicePrice()
    {
        if (BuzConst.DINGDAN_CHANGE_TYPE_SM.equals(model.getChangeType().trim()))
        {
            String[] keys = { "title", "key" };
            Object[] values = new Object[] { BuzConst.CONFIG_INFO, BuzConst.CONFIG_SERVER_PRICE };
            List<Dict> dl = commonService.search(Dict.class, keys, values);
            if (null != dl && dl.size() > 0)
            {
                Dict d = dl.get(0);
                model.setServerPrice(d.getValue());
            }
            else
            {
                model.setServerPrice("11");
            }
        }
        else
        {
            model.setServerPrice(null);
        }
    }

    /***
     * 人工上门更换
     * @return
     */
    public String changeTypeManul()
    {
        if (null != model)
        {
            setServicePrice();
            addModelSessionCookie(model);
            setNow();
            if (log.isDebugEnabled())
            {
                log.debug("人工上门更换订单：" + model);
            }
            return "changeTypeManul";
        }
        else
        {
            model = getModelSessionCookie();
            if (null != model)
            {
                setServicePrice();
                addModelSessionCookie(model);
                setNow();
                if (log.isDebugEnabled())
                {
                    log.debug("人工上门更换订单：" + model);
                }
                return "changeTypeManul";
            }
            log.error("订单数据缺失ERROR");
            return "outTimeError";
        }
    }

    /**去订单确认界面****/
    public String toConfirm()
    {
        if (null == model)
        {
            log.debug("最后提交");
            model = getModelSessionCookie();
        }
        if (null != model)
        {
            if (!checkModelPrice())
            {
                log.debug("EEEEEE:价格被修改，有数据丢失");
            }
            else
            {
                setServicePrice();
                addModelSessionCookie(model);
                if (log.isDebugEnabled())
                {
                    log.debug("提交订单：" + model);
                }
                if (null != getSessionAttribute("wxid"))
                {
                    wxid = getSessionAttribute("wxid").toString();
                    model.setUserId(wxid);
                    log.debug("微信id is " + wxid);
                }
                model.setState("0");// 0初始状态
                model.setCrateDate(DateUtils.getCurrDate(null));
                model = doColumnFilter(model);//针对订单类型对一些字段做过滤
                model = dingDanService.addDingdan(model);
                return "toConfirm";
            }
        }
        return "outTimeError";
    }

    //该品牌型号电池，价格是否被修改做校验
    private boolean checkModelPrice()
    {
        //TODO 更换类型检查，暂时不做

        if (!StringUtils.isBlank(model.getPrice()))
        {
            Battery b = batteryService.queryBettyById(model.getDianchiId(), model.getProvince(), model.getCity(), model.getTown());
            if (null != b)
            {
                if (!StringUtils.isBlank(b.getOurPrice()))
                {
                    if (b.getOurPrice().equals(model.getPrice()))
                    {
                        return true;
                    }
                    else
                    {
                        model.setPrice(b.getOurPrice());
                        log.debug("不好有高人:价格被修改，重新查询为主");
                        return true;
                    }
                }
            }
            log.debug("尼玛，该种电池压根不存在" + model);
        }

        return false;
    }

    /**转换经纬度坐标系接口
     * 测试方法
     * @throws Exception */
    public String getcCnvertLatLng() throws Exception
    {
        String url = BuzConst.HTTP_BAIDU_CONVERT_URL;
        Double lat = Double.parseDouble(getRequestParameter("lat"));
        Double lng = Double.parseDouble(getRequestParameter("lng"));
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", true);
        if (null != lat && null != lng)
        {
            String http = url + "&y=" + lat + "&x=" + lng;
            String resp;
            try
            {
                resp = MySecureProtocolSocketFactory.get(http);
                JSONObject jsonObj = JSONObject.fromObject(resp.toString());
                if (null != jsonObj)
                {
                    if (jsonObj.get("error").toString().equals("0"))
                    {
                        String x = (String) jsonObj.get("x");
                        String y = (String) jsonObj.get("y");
                        log.debug("选择服务前调研纠偏接口：纠偏数据结果未解码为 x：" + x + ",y:" + y);
                        map.put("gpslng", Double.parseDouble(EncryptTool.getFromBASE64(x)));
                        map.put("gpslat", Double.parseDouble(EncryptTool.getFromBASE64(y)));
                    }
                }
                url = BuzConst.HTTP_BAIDU_CONVERT_URL2;
                http = url + "&y=" + lat + "&x=" + lng;
                resp = MySecureProtocolSocketFactory.get(http);
                jsonObj = JSONObject.fromObject(resp.toString());
                if (null != jsonObj)
                {
                    if (jsonObj.get("error").toString().equals("0"))
                    {
                        String x = (String) jsonObj.get("x");
                        String y = (String) jsonObj.get("y");
                        log.debug("选择服务前调研纠偏接口：纠偏数据结果未解码为 x：" + x + ",y:" + y);
                        map.put("gglng", Double.parseDouble(EncryptTool.getFromBASE64(x)));
                        map.put("gglat", Double.parseDouble(EncryptTool.getFromBASE64(y)));
                    }
                }
            }
            catch (Exception e)
            {
                map.put("success", false);
                map.put("msg", "调用远程接口异常");
                log.debug("选择服务前调研纠偏接口： 调用百度纠偏接口失败！");
                e.printStackTrace();
            }
        }
        else
        {
            map.put("msg", "传入经纬度异常");
            map.put("success", false);
            log.debug("已经做了纠偏处理。。。。");
        }
        outJson(map);
        return null;
    }

    @Required
    @Resource
    public void setCommonService(ICommonService commonService)
    {
        this.commonService = commonService;
    }

    public Long getId()
    {
        return id;
    }

    public void setId(Long id)
    {
        this.id = id;
    }

    @Required
    @Resource
    public void setBatteryService(BatteryService batteryService)
    {
        this.batteryService = batteryService;
    }

    @Required
    @Resource
    public void setMenDianService(MenDianService menDianService)
    {
        this.menDianService = menDianService;
    }

    public Double getLat()
    {
        return lat;
    }

    public void setLat(Double lat)
    {
        this.lat = lat;
    }

    public Double getLng()
    {
        return lng;
    }

    public void setLng(Double lng)
    {
        this.lng = lng;
    }

    public DingDan getModel()
    {
        return model;
    }

    public void setModel(DingDan model)
    {
        this.model = model;
    }

    public String getWxid()
    {
        return wxid;
    }

    public void setWxid(String wxid)
    {
        this.wxid = wxid;
    }

    @Required
    @Resource
    public void setDingDanService(DingDanService dingDanService)
    {
        this.dingDanService = dingDanService;
    }

    public String getLianxiName()
    {
        return lianxiName;
    }

    public void setLianxiName(String lianxiName)
    {
        this.lianxiName = lianxiName;
    }

    public String getLianxiKefuTel()
    {
        return lianxiKefuTel;
    }

    public void setLianxiKefuTel(String lianxiKefuTel)
    {
        this.lianxiKefuTel = lianxiKefuTel;
    }

    public String getLianxiAddr()
    {
        return lianxiAddr;
    }

    public void setLianxiAddr(String lianxiAddr)
    {
        this.lianxiAddr = lianxiAddr;
    }

    public String getGzhId()
    {
        return gzhId;
    }

    public void setGzhId(String gzhId)
    {
        this.gzhId = gzhId;
    }

    public String getToken()
    {
        return token;
    }

    public void setToken(String token)
    {
        this.token = token;
    }

    public List<DingDan> getDingdans()
    {
        return dingdans;
    }

    public void setDingdans(List<DingDan> dingdans)
    {
        this.dingdans = dingdans;
    }

    public String getProvince()
    {
        return province;
    }

    public void setProvince(String province)
    {
        this.province = province;
    }

    public String getCity()
    {
        return city;
    }

    public void setCity(String city)
    {
        this.city = city;
    }

    public String getTown()
    {
        return town;
    }

    public void setTown(String town)
    {
        this.town = town;
    }

    public String getState()
    {
        return state;
    }

    public void setState(String state)
    {
        this.state = state;
    }

    public ICommonService getCommonService()
    {
        return commonService;
    }

    @Required
    @Resource
    public void setCheXingCityService(CheXingCityService cheXingCityService)
    {
        this.cheXingCityService = cheXingCityService;
    }

    public String getNowDate()
    {
        return nowDate;
    }

    public void setNowDate(String nowDate)
    {
        this.nowDate = nowDate;
    }

    public String getNowHour()
    {
        return nowHour;
    }

    public void setNowHour(String nowHour)
    {
        this.nowHour = nowHour;
    }

    public List<Battery> getBetteryList()
    {
        return betteryList;
    }

    public void setBetteryList(List<Battery> betteryList)
    {
        this.betteryList = betteryList;
    }

    public String getJson()
    {
        return json;
    }

    public void setJson(String json)
    {
        this.json = json;
    }

    public String getAppid()
    {
        return appid;
    }

    public void setAppid(String appid)
    {
        this.appid = appid;
    }

    public String getRedirect_uri()
    {
        return redirect_uri;
    }

    public void setRedirect_uri(String redirectUri)
    {
        redirect_uri = redirectUri;
    }

    public int getLevel()
    {
        return level;
    }

    public void setLevel(int level)
    {
        this.level = level;
    }

    public String getBetteryListJson()
    {
        return betteryListJson;
    }

    public void setBetteryListJson(String betteryListJson)
    {
        this.betteryListJson = betteryListJson;
    }

    public String getDingdansJson()
    {
        return dingdansJson;
    }

    public void setDingdansJson(String dingdansJson)
    {
        this.dingdansJson = dingdansJson;
    }

}
